#coding=utf-8
#!/usr/bin/python

"""
主线程，管理子线程



"""

import threading
import time,sys,os

import test2 as wui
import wx



thr_lists= [] #线程容器
thr_id= {}    #线程id容器
run_thr=1        #1 表示允许，0 表示离开

def thr_unall():
    """  通知线程 离开 """
    global run_thr
    #上锁
    mutex.acquire()
    #修改
    run_thr = 0
    #解锁
    mutex.release()
    # 直接退 没用
    #print '--sys.exit()--'
    #sys.exit()
    #exit()
    
def thr_mk(targ):
    """ 创建线程 """
    global thr_lists
    # 创建线程对象
    new_thr = thr_test(targ)  #内循环10次  调用  全局类实例的 db_obj.test(threadname, x)
    #print  '----start thr----',targ
    new_thr.start()
    #print  '----thr end' ,targ
    
    #纪录创建的thr
    thr_lists.append(new_thr)
    

def thr_exit():
    """ 等待子线程结束 """
    for ithr in thr_lists:
        ithr.join()  
    print "-thr_exit-"
    
def set_thr_lists(ind,name,val):
    """ 设置 val"""
    global thr_id
    #获取 锁
    mutex.acquire()
    thr_id[ind] = val
    # 释放静态锁
    mutex.release()
def del_thr_lists(ind):
    """ 设置 val"""
    global thr_id
    #获取 锁
    mutex.acquire()
    del(thr_id[ind])
    # 释放静态锁
    mutex.release()

def len_thr_lists( ):
    """ 设置 val"""
    global thr_id
    #获取 锁
    mutex.acquire()
    ret_len = len(thr_id)
    # 释放静态锁
    mutex.release()
    return ret_len

#等待，通行
cond = threading.Condition()
#资源锁
mutex =  threading.Lock()




gs_dic={}

gs_dic['mag']=1 #管理者

gs_dic['wx']=0
gs_dic['wx2']=0
gs_dic['wx3']=0


import thread
import inspect
import ctypes


def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
        raise SystemError("PyThreadState_SetAsyncExc failed")


class thr_test(threading.Thread):
    #实例化类 是的参数 2个
    def __init__(self, targ):
        threading.Thread.__init__(self)
        self.targ = targ
        
    def run(self):
        global thr_id
        u"线程实际工作"
        # 返回 Thread-  
        threadname = threading.currentThread().getName()
        
        tid=thread.get_ident()
        
        #设置值
        set_thr_lists(threadname,0,{'tid':tid,"targ":self.targ,"obj":threadname})

        
        #_async_raise(tid, NameError)#？？？？
        #实际操作
        #eval('aa()')

        if 'mag' == self.targ :
            thr_mag()

        if 'wx' == self.targ :
            wx()
        if 'wx2' == self.targ :
            wx2()
        if 'wx3' == self.targ :
            wx3()
        print "thr " , self.targ , "exit;--"

app = wx.PySimpleApp()


def thr_mag():
    """ 管理者  最先开启，最后退出 """
    #处理循环
    while 1 :
        """ 推出判断"""
        if thr_run() and len_thr_lists()==1:
            break
        #获取 操作权
        cond.acquire()
          
        #释放前的暂停时间
        time.sleep(1)
        cond_fun()
        #do
            
def wx():
    tname=threading.currentThread().getName()
    print "name==========",tname,"====="
    
    #处理循环
    while 1 :
        """ 推出判断"""
        if thr_run():
            del_thr_lists(tname)
            break
        #获取 操作权
        cond.acquire()
        if gs_dic['wx']==0:
            print "-cond.wait1-"
            cond.wait()
        #cond.notifyAll() #我收到
        #cond.release()#释放
        cond_fun()
        #do
        print "wx---do"
        time.sleep(10)
            
def wx2():
    db_obj = wui.MainWindow()
    db_obj.test()
    app.MainLoop()
    
    
def wx3():
    tname=threading.currentThread().getName()
    print "name==========",tname,"====="
    #处理循环
    while 1 :
        """ 推出判断"""
        if thr_run():
            del_thr_lists(tname)
            break
        #获取 操作权
        cond.acquire()
        if gs_dic['wx3']==0:
            print "-cond.wait3-"
            cond.wait()
        #cond.notifyAll() #我收到
        #cond.release()#释放
        cond_fun()
        #do
        print "wx3---do"
        
def cond_fun():
    """ 通知 并且释放 """
    cond.notifyAll() #我收到
    cond.release()#释放

def thr_run():
    """ 检查 线程 是否应该推出"""
    print "run_thr=" ,run_thr
    return not run_thr

if __name__ == '__main__':
    

    print __file__ ,':the end'